package application

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/yyangl/yoyo/e"
	"io/ioutil"
)

type BaseController struct {
	app    *Application
	router *gin.RouterGroup
}

func (c *BaseController) SetRouter(router *gin.RouterGroup) {
	c.router = router
}
func (c *BaseController) SetApplication(app *Application) {
	c.app = app
}
func (c *BaseController) Json(ctx *gin.Context, status int, obj interface{}) {
	ctx.JSON(status, obj)
}

func (c *BaseController) GetApp() *Application {
	return c.app
}

func (c *BaseController) OK(ctx *gin.Context, obj interface{}) {
	data := map[string]interface{}{
		"code":    e.Success,
		"message": "success",
		"data":    obj,
	}
	c.Json(ctx, httpOK, data)
}

func (c *BaseController) Err(ctx *gin.Context, message string) {
	data := map[string]interface{}{
		"code":    e.Error,
		"message": message,
	}
	c.Json(ctx, httpOK, data)
}

func (c *BaseController) ServiceErr(ctx *gin.Context) {
	data := map[string]interface{}{
		"code":    e.ErrorService,
		"message": e.GetMeg(e.ErrorService),
	}
	c.Json(ctx, httpOK, data)
}

func (c *BaseController) ParamErr(ctx *gin.Context) {
	data := map[string]interface{}{
		"code":    e.ErrorNotExistToken,
		"message": e.GetMeg(e.ErrorParams),
	}
	c.Json(ctx, httpOK, data)
}

func (c *BaseController) Get(path string, handlerFunc ...gin.HandlerFunc) {
	c.router.GET(path, handlerFunc...)
}

func (c *BaseController) Post(path string, handlerFunc ...gin.HandlerFunc) {
	c.router.POST(path, handlerFunc...)
}

func (c *BaseController) Delete(path string, handlerFunc ...gin.HandlerFunc) {
	c.router.DELETE(path, handlerFunc...)
}

func (c *BaseController) Patch(path string, handlerFunc ...gin.HandlerFunc) {
	c.router.PATCH(path, handlerFunc...)
}

func (c *BaseController) PostData(ctx *gin.Context) map[string]interface{} {
	var d = make(map[string]interface{})
	// handler post from params
	err := ctx.Request.ParseForm()
	if err == nil {
		for k, v := range ctx.Request.PostForm {
			d[k] = v
		}
	}

	// handler post json params
	var body = make(map[string]interface{})
	data, _ := ioutil.ReadAll(ctx.Request.Body)
	err = json.Unmarshal(data, &body)
	if err == nil {
		for k, v := range body {
			d[k] = v
		}
	}
	return d
}

func (c *BaseController) SafeRead(source map[string]interface{}, key string, def interface{}) interface{} {
	if _, ok := source[key]; ok {
		return source[key]
	}
	return def
}
